package com.hh.db.core

import android.content.Context
import com.hh.db.BuildConfig
import com.hh.db.entity.ClockInRecord
import com.hh.db.entity.ClockMonth
import com.hh.db.entity.MyObjectBox
import com.hh.db.entity.TODODetail
import com.hh.db.entity.TODOItem
import io.objectbox.Box
import io.objectbox.BoxStore
import io.objectbox.Property
import io.objectbox.android.Admin
import io.objectbox.query.QueryCondition

/**
 * Create By hHui on 2025/4/7 10:04
 *
 * @description
 */
object ObjectBoxUtil {
    private lateinit var store: BoxStore
    lateinit var clockInRecordBox: Box<ClockInRecord>
    lateinit var clockMonthBox: Box<ClockMonth>
    lateinit var todoItemBox: Box<TODOItem>
    lateinit var todoDetailBox: Box<TODODetail>

    /**
     * 初始化
     */
    fun init(context: Context) {
        store = MyObjectBox.builder().androidContext(context).build()
        clockInRecordBox = store.boxFor(ClockInRecord::class.java)
        clockMonthBox = store.boxFor(ClockMonth::class.java)
        todoItemBox = store.boxFor(TODOItem::class.java)
        todoDetailBox = store.boxFor(TODODetail::class.java)

        if (BuildConfig.DEBUG) {
            Admin(store).start(context)
        }
    }

    /**
     * 清除所有数据
     */
    fun clear() {
        clockInRecordBox.removeAll()
        clockMonthBox.removeAll()
        todoItemBox.removeAll()
        todoDetailBox.removeAll()
    }

    /**
     * 查询列表
     * @param queryCondition 查询条件
     * @param orderType 排序类型
     * @param property 排序字段
     */
    fun <T> Box<T>.queryList(queryCondition: QueryCondition<T>, orderType: OrderType? = null, property: Property<T>? = null): MutableList<T> {
        val query = this.query(queryCondition)
        property?.let {
            orderType?.let { type ->
                if (type == OrderType.ASC) {
                    query.order(property)
                } else {
                    query.orderDesc(property)
                }
            }
        }
        return query.build().let {
            val list = it.find()
            it.close()
            list
        }
    }

    /**
     * 查询单个数据
     */
    fun <T> Box<T>.queryFirst(queryCondition: QueryCondition<T>): T? {
        return this.query(queryCondition).build().let {
            val result = it.findFirst()
            it.close()
            result
        }
    }

    enum class OrderType {
        ASC,
        DESC
    }

}